package com.boot.demohttp.compont;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
@Configuration
public class ForWardCompont implements HandlerInterceptor {
    @Autowired
    RestTemplate restTemplate;
    @Value("${server.forward-url}")
    String forwardUrl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = String.format("%s%s", forwardUrl, request.getRequestURI());
        log.info("{}", request.getRequestURI());

        ResponseEntity<String> forEntity ;
        if (request.getMethod().equals("GET")) {
            forEntity = restTemplate.getForEntity(url, String.class);
        }else {
            forEntity = restTemplate.postForEntity(url, null,String.class);
        }
        response.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器

        if (forEntity.getStatusCode().equals(HttpStatus.OK)) {

            PrintWriter out = response.getWriter();//获取PrintWriter输出流
            out.print(forEntity.getBody());
            out.close();
            out.flush();
        } else {
            response.setStatus(forEntity.getStatusCode().value());
        }
        return false;
    }
}
